package com.gcb.controller;

import com.gcb.constant.MessageConstant;
import com.gcb.constant.RedisMessageConstant;
import com.gcb.entity.Result;
import com.gcb.pojo.Order;
import com.gcb.service.OrderService;
import com.gcb.util.SmsUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Map;

/**
 * @Author 35235
 * @Date 2021/8/12 20:11
 * @Version 1.0
 */
@RestController
@RequestMapping("/order")
public class OrderController {
@Autowired
    private JedisPool jedisPool;
    @DubboReference
    private OrderService orderService;
    // 在线体检预约
    @RequestMapping("/submit.do")
    public Result submit(@RequestBody Map map){
        String telephone = (String) map.get("telephone");
        // 从Redis中获取保存的验证码
        String validateCodeInRedis = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_ORDER);
        String validateCode = (String) map.get("validateCode");

        // 将用户输入的验证码和Redis中保存的验证码进行比对
        if(validateCodeInRedis != null && validateCode != null && validateCode.equals(validateCodeInRedis)){
            // 如果比对成功，调用服务完成预约业务处理
            // 设置预约类型，分为微信预约、电话预约
            map.put("orderType", Order.ORDERTYPE_WEIXIN);
            Result result = null;
            try{
                // 通过Dubbo远程调用服务实现在线预约业务处理
                result = orderService.order(map);
            }catch (Exception e){
                e.printStackTrace();
                return result;
            }
            if(result.isFlag()){
                // 预约成功，可以为用户发送短信
                try{
                    SmsUtils.sendShortMessage(SmsUtils.ORDER_NOTICE, telephone, (String) map.get("orderDate"));
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            return result;
        }else{
            // 如果比对不成功，返回结果给页面
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
    }
}
